﻿#include "NewDataBase.h"
#include "ui_NewDataBase.h"
#include "mainwindow.h"

NewDataBase::NewDataBase(QWidget *parent, MainWindow *win) :
    QDialog(parent),
    ui(new Ui::NewDataBase)
{
    ui->setupUi(this);
    setWindowTitle(QString::fromLocal8Bit("新建数据库"));
    connect(ui->pushButtonCancel, SIGNAL(clicked(bool)), this, SLOT(reject()));
    m_win = win;
}

NewDataBase::~NewDataBase()
{
    if(m_MeasureSpec != nullptr)
    {
        delete m_MeasureSpec;
        m_MeasureSpec = nullptr;
    }
    delete ui;
}

void NewDataBase::on_pushButtonOK_clicked()
{
    if( ui->lineEdit_sqlPath->text().isEmpty())
    {
        QMessageBox::about(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("请选择或输入目录"));
        return;
    }
    QFileInfo fi(ui->lineEdit_sqlPath->text());
    if( !fi.isDir() )
    {
        QMessageBox::about(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("目录不存在"));
        return;
    }
    if( ui->lineEdit_sqlName->text().isEmpty())
    {
        QMessageBox::about(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("数据库名称不能为空"));
        return;
    }
    if( ui->spinBox->value() <= 0)
    {
        QMessageBox::about(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("测点数量不能小于等于0"));
        return;
    }
    //创建文件并创建表格写入信息
    QString fileName = ui->lineEdit_sqlPath->text() + "/" + ui->lineEdit_sqlName->text() + ".db";
    if( QFileInfo(fileName).isFile() )
    {
        QMessageBox::about(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("文件已存在，请重新输入数据库名称"));
        return;
    }
    done(1);
    m_MeasureSpec = new MeasureSpec(this, m_win);
    m_MeasureSpec->setData(fileName, ui->lineEdit_sqlName->text(), ui->spinBox->value(), ui->textEdit->toPlainText());
    m_MeasureSpec->createDataBase();
    m_MeasureSpec->exec();
    this->close();
}

void NewDataBase::on_toolButton_findDir_clicked()
{
    QString fileName = QFileDialog::getExistingDirectory(this);
    ui->lineEdit_sqlPath->setText(fileName);
}
